: The Input (Form Input) element

您所在的位置:网站首页 el-input type=file : The Input (Form Input) element

: The Input (Form Input) element

2024-06-18 13:34| 来源: 网络整理| 查看: 265

Warning: Client-side validation is useful, but it does not guarantee that the server will receive valid data. If the data must be in a specific format, always verify it also on the server-side, and return a 400 HTTP response if the format is invalid.

In addition to using CSS to style inputs based on the :valid or :invalid UI states based on the current state of each input, as noted in the UI pseudo-classes section above, the browser provides for client-side validation on (attempted) form submission. On form submission, if there is a form control that fails constraint validation, supporting browsers will display an error message on the first invalid form control; displaying a default message based on the error type, or a message set by you.

Some input types and other attributes place limits on what values are valid for a given input. For example, means only the number 2, 4, 6, 8, or 10 are valid. Several errors could occur, including a rangeUnderflow error if the value is less than 2, rangeOverflow if greater than 10, stepMismatch if the value is a number between 2 and 10, but not an even integer (does not match the requirements of the step attribute), or typeMismatch if the value is not a number.

For the input types whose domain of possible values is periodic (that is, at the highest possible value, the values wrap back around to the beginning rather than ending), it's possible for the values of the max and min properties to be reversed, which indicates that the range of permitted values starts at min, wraps around to the lowest possible value, then continues on until max is reached. This is particularly useful for dates and times, such as when you want to allow the range to be from 8 PM to 8 AM:

html

Specific attributes and their values can lead to a specific error ValidityState:

Validity object errors depend on the attributes and their values: Attribute Relevant property Description max validityState.rangeOverflow Occurs when the value is greater than the maximum value as defined by the max attribute maxlength validityState.tooLong Occurs when the number of characters is greater than the number allowed by the maxlength property min validityState.rangeUnderflow Occurs when the value is less than the minimum value as defined by the min attribute minlength validityState.tooShort Occurs when the number of characters is less than the number required by the minlength property pattern validityState.patternMismatch Occurs when a pattern attribute is included with a valid regular expression and the value does not match it. required validityState.valueMissing Occurs when the required attribute is present but the value is null or radio or checkbox is not checked. step validityState.stepMismatch The value doesn't match the step increment. Increment default is 1, so only integers are valid on type="number" is step is not included. step="any" will never throw this error. type validityState.typeMismatch Occurs when the value is not of the correct type, for example an email does not contain an @ or a url doesn't contain a protocol.

If a form control doesn't have the required attribute, no value, or an empty string, is not invalid. Even if the above attributes are present, with the exception of required, an empty string will not lead to an error.

We can set limits on what values we accept, and supporting browsers will natively validate these form values and alert the user if there is a mistake when the form is submitted.

In addition to the errors described in the table above, the validityState interface contains the badInput, valid, and customError boolean readonly properties. The validity object includes:

validityState.valueMissing validityState.typeMismatch validityState.patternMismatch validityState.tooLong validityState.tooShort validityState.rangeUnderflow validityState.rangeOverflow validityState.stepMismatch validityState.badInput validityState.valid validityState.customError

For each of these Boolean properties, a value of true indicates that the specified reason validation may have failed is true, with the exception of the valid property, which is true if the element's value obeys all constraints.

If there is an error, supporting browsers will both alert the user and prevent the form from being submitted. A word of caution: if a custom error is set to a truthy value (anything other than the empty string or null), the form will be prevented from being submitted. If there is no custom error message, and none of the other properties return true, valid will be true, and the form can be submitted.

jsfunction validate(input) { let validityState_object = input.validity; if (validityState_object.valueMissing) { input.setCustomValidity("A value is required"); } else if (validityState_object.rangeUnderflow) { input.setCustomValidity("Your value is too low"); } else if (validityState_object.rangeOverflow) { input.setCustomValidity("Your value is too high"); } else { input.setCustomValidity(""); } }

The last line, setting the custom validity message to the empty string is vital. If the user makes an error, and the validity is set, it will fail to submit, even if all the values are valid, until the message is null.

Custom validation error example

If you want to present a custom error message when a field fails to validate, you need to use the Constraint Validation API available on (and related) elements. Take the following form:

html Enter username (upper and lowercase letters): Submit

The basic HTML form validation features will cause this to produce a default error message if you try to submit the form with either no valid filled in, or a value that does not match the pattern.

If you wanted to instead display custom error messages, you could use JavaScript like the following:

jsconst nameInput = document.querySelector("input"); nameInput.addEventListener("input", () => { nameInput.setCustomValidity(""); nameInput.checkValidity(); }); nameInput.addEventListener("invalid", () => { if (nameInput.value === "") { nameInput.setCustomValidity("Enter your username!"); } else { nameInput.setCustomValidity( "Usernames can only contain upper and lowercase letters. Try again!", ); } });

The example renders like so:

In brief:

We check the valid state of the input element every time its value is changed by running the checkValidity() method via the input event handler. If the value is invalid, an invalid event is raised, and the invalid event handler function is run. Inside this function we work out whether the value is invalid because it is empty, or because it doesn't match the pattern, using an if () block, and set a custom validity error message. As a result, if the input value is invalid when the submit button is pressed, one of the custom error messages will be shown. If it is valid, it will submit as you'd expect. For this to happen, the custom validity has to be cancelled, by invoking setCustomValidity() with an empty string value. We therefore do this every time the input event is raised. If you don't do this, and a custom validity was previously set, the input will register as invalid, even if it currently contains a valid value on submission.

Note: Always validate input constraints both client side and server side. Constraint validation doesn't remove the need for validation on the server side. Invalid values can still be sent by older browsers or by bad actors.

Note: Firefox supported a proprietary error attribute — x-moz-errormessage — for many versions, which allowed you set custom error messages in a similar way. This has been removed as of version 66 (see Firefox bug 1513890).



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3